<%--
  Created by IntelliJ IDEA.
  User: 薛之谦
  Date: 2025/9/23
  Time: 10:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>
<style>
    .content-area {
        background-color: #ffffff;
        min-height: calc(100vh - 56px);
    }

    .stats-card {
        transition: transform 0.2s;
    }

    .stats-card:hover {
        transform: translateY(-5px);
    }

    .question-item {
        border-left: 4px solid #0d6efd;
        transition: all 0.3s;
    }

    .question-item:hover {
        box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
    }

    .filter-section {
        background-color: #f8f9fa;
        border-radius: 8px;
    }

    .bi::before {
        vertical-align: -0.1em;
    }
</style>
</head>
<body>
<div class="container-fluid">
    <!-- 主内容区 -->
    <div class="content-area p-4">
        <!-- 页面标题和操作按钮 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-journal-text"></i>
                <span>题库管理</span>
            </h2>
            <div>
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uploadModal">
                    <i class="bi bi-cloud-upload"></i> 批量导入
                </button>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addQuestionModal">
                    <i class="bi bi-plus-circle"></i> 新增题目
                </button>
                <button class="btn btn-info">
                    <i class="bi bi-download"></i> 导出题库
                </button>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="row mb-4" id="statsCardsContainer">
            <!-- 卡片将通过JavaScript动态生成 -->
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section p-3 mb-4">
            <form action="${pageContext.request.contextPath}/questionstoremanage/search" method="get" id="searchForm">
                <div class="row g-3">
                    <div class="col-md-3">
                        <select class="form-select" id="courseFilter" name="courseId">
                            <option value="">所有课程</option>
                            <!-- 通过JavaScript动态加载 -->
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="questionTypeFilter" name="questionTypeId">
                            <option value="">所有题型</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <div class="input-group">
                            <input type="text" class="form-control" placeholder="搜索题目..." name="searchText" value="${searchText}">
                            <button class="btn btn-primary" type="submit" id="searchBtn">
                                <i class="bi bi-search"></i> 查询
                            </button>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-secondary" type="button" id="resetBtn">
                            <i class="bi bi-arrow-clockwise"></i> 重置
                        </button>
                    </div>
                </div>
            </form>
        </div>



        <!-- 题目列表 -->
        <div class="card">
            <div class="card-header bg-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">题目列表</h5>
                    <div>
                        <button class="btn btn-sm btn-outline-danger" id="batchDelete">
                            <i class="bi bi-trash"></i> 批量删除
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <!-- 题目项 -->
                <div class="row align-items-center mb-2">
                    <div class="col-md-2">
                        <input class="form-check-input" type="checkbox" id="selectAll">
                        <label for="selectAll" class="ms-1">全选</label>
                    </div>
                </div>
                <!-- 题目项 -->
                <c:forEach items="${page.items}" var="question" varStatus="status">
                    <div class="question-item p-3 mb-3 border rounded">
                        <div class="row align-items-center">
                            <div class="col-md-1">
                                <input class="form-check-input" type="checkbox">
                            </div>
                            <div class="col-md-7">
                                <h6 class="mb-1">${(page.pageIndex - 1) * page.pageSize + status.count}. ${question.title}</h6>
                                <p class="text-muted mb-0">
                                    <span class="badge bg-primary">${question.typeName}</span>
                                    <span class="badge bg-info">${question.courseName}</span>
<%--                                    <small class="ms-2">更新时间：2024-01-15</small>--%>
                                </p>
                            </div>
                            <div class="col-md-4 text-end question-bar" data-id="${question.id}">
                                <button class="btn btn-sm btn-outline-primary" id="getByIdBtn">
                                    <i class="bi bi-eye"></i> 查看
                                </button>
                                <button class="btn btn-sm btn-outline-warning editBtn" id="editBtn"
                                        data-bs-toggle="modal" data-bs-target="#editModal">
                                    <i class="bi bi-pencil"></i> 编辑
                                </button>
                                <button class="btn btn-sm btn-outline-danger delBtn" id="delBtn">
                                    <i class="bi bi-trash"></i> 删除
                                </button>
                            </div>
                        </div>
                    </div>
                </c:forEach>
            </div>

            <!-- 分页 -->
            <jsp:include page="pagination.jsp">
                <jsp:param name="courseId" value="${searchCourseId}" />
                <jsp:param name="questionTypeId" value="${searchQuestionTypeId}" />
                <jsp:param name="searchText" value="${searchText}" />
            </jsp:include>
        </div>
    </div>
</div>

<!-- 批量上传模态框 -->
<div class="modal fade" id="uploadModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">批量导入题目</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">选择文件格式</label>
                    <select class="form-select">
                        <option>Excel (.xlsx)</option>
                        <option>CSV (.csv)</option>
                        <option>Word (.docx)</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">上传文件</label>
                    <input class="form-control" type="file" accept=".xlsx,.csv,.docx" multiple>
                </div>

                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    <a href="#">下载模板文件</a> 查看导入格式要求
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="uploadCancel">取消
                </button>
                <button type="button" class="btn btn-primary" id="uploadBtn">开始导入</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑模态框 -->
<!-- Modal -->
<div class="modal fade" id="editModal" data-bs-backdrop="static" data-bs-keyboard="false"
     tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">题型详情</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="Close"></button>
            </div>
            <div class="modal-body flex-wrap" style="padding-left: 60px; padding-right: 60px;">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消
                </button>
                <button type="button" class="btn btn-primary" id="editModalBtn">编辑</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addQuestionModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">请输入信息</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3 w-100">
                    <label for="title" class="form-label">title</label>
                    <input type="text" class="form-control" id="title" placeholder="请输入题目"/>
                </div>
                <div class="mb-3 w-100">
                    <label for="option" class="form-label">option</label>
                    <input type="text" class="form-control" id="option" placeholder="请输入选项"/>
                </div>
                <div class="mb-3 w-100">
                    <label for="answer" class="form-label">answer</label>
                    <input type="text" class="form-control" id="answer" placeholder="请输入答案"/>
                </div>
                <div class="mb-3 w-100">
                    <label for="typeId" class="form-label">type</label>
                    <select class="form-select" id="typeId" name="typeId">
                        <option value="0">请选择试题类型</option>
                        <option value="1">单选题</option>
                        <option value="2">多选题</option>
                        <option value="3">判断题</option>
                    </select>
                </div>
                <div class="mb-3 w-100">
                    <label for="courseId" class="form-label">course</label>
                    <select class="form-select" id="courseId" name="courseId">
                        <option value="0">请选择试题所属课程</option>
                        <option value="1">Java</option>
                        <option value="2">Python</option>
                        <option value="3">数据库</option>
                        <option value="4">前端</option>
                        <option value="5">Linux</option>
                    </select>
                </div>
                <div class="mb-3 w-100">
                    <label class="form-check-label" for="state">状态</label>
                    <div class="form-check form-switch" style="width: 50%;">
                        <input class="form-check-input start-info" id="state" type="checkbox" role="switch">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消
                </button>
                <button type="button" class="btn btn-primary" id="addModalBtn">添加</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 上传模态框
        const $uploadModal = $("#uploadModal");
        // 上传按钮
        const $uploadBtn = $("#uploadBtn");
        // 上传文件选择框
        const fileInput = document.querySelector("#uploadModal input[type='file']");
        // 题库删除按钮
        const $deleteBtns = $(".delBtn");
        // 添加模态框按钮
        const $addQuestionModal = $("#addQuestionModal");
        // 添加模态框按钮
        const $addModalBody = $addQuestionModal.find(".modal-body");
        // 添加模态框按钮
        const $addModalBtn = $addQuestionModal.find("#addModalBtn");
        // 题库所有修改按钮
        const $editBtns = $(".editBtn");
        // 修改模态框按钮
        const $editModal = $("#editModal");
        // 修改模态框body
        const $editModalBody = $editModal.find(".modal-body");
        // 添加模态框按钮
        const $editModalBtn = $editModal.find("#editModalBtn");
        // 全选按钮
        const $selectAllBtn = $("#selectAll");
        // 题库所有多选框
        const $questionItemSelects = $(".question-item").find("input[type='checkbox']");
        // 批量删除按钮
        const $batchDeleteBtn = $("#batchDelete");

        // 批量删除按钮事件
        $batchDeleteBtn.click(() => {
            const questionIds = [];
            $questionItemSelects.each(function () {
                if ($(this).prop('checked')) {
                    questionIds.push($(this).closest("div.row").find(".question-bar").data("id"));
                }
            });
            $.post(
                "http://localhost:8080/examproject/examquestionmanage/deleteBatch",
                {
                    questionIds: questionIds,
                }, null, "json").done(result => {
                if (result.code) {
                    alert(result.message.toString());
                    window.location.reload();
                } else {
                    alert(result.message);
                }
            }).fail(function () {
                alert(result.message);
            });
        });


        // 全选按钮
        $selectAllBtn.click(function () {
            const isChecked = $(this).prop('checked');
            $questionItemSelects.prop('checked', isChecked);
        });
        // 反选逻辑
        $questionItemSelects.click(function () {
            const allChecked = $questionItemSelects.filter(':checked').length === $questionItemSelects.length;
            $selectAllBtn.prop('checked', allChecked);
        });

        // 定义文件上传按钮的功能
        const uploadBtnHandler = function () {
            // 获取文件输入元素
            const files = fileInput.files;

            // 检查是否选择文件
            if (files.length === 0) {
                alert("请选择要上传的文件");
                return;
            }

            // 检查文件类型和大小
            const allowedTypes = ['xlsx', 'csv', 'docx'];
            const maxSize = 10 * 1024 * 1024; // 10MB
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const fileExtension = file.name.split('.').pop().toLowerCase();

                if (!allowedTypes.includes(fileExtension)) {
                    alert("只允许上传 Excel (.xlsx)、CSV (.csv) 或 Word (.docx) 文件");
                    return;
                }

                if (file.size > maxSize) {
                    alert("文件大小不能超过10MB");
                    return;
                }
            }
            // 创建FormData对象
            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append("files", files[i]);
            }
            // 显示上传对象
            $uploadBtn.prop("disabled", true).text("上传中...");
            // 发送ajax请求 $.ajax返回deferred对象，不是标准的promise对象，所以不能用done方法
            $.ajax({
                url: "${pageContext.request.contextPath}/examquestionmanage/upload",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
            }).done((result) => {
                alert("文件上传成功" + result.toString());
                $uploadModal.modal('hide');
                // 重置表单
                fileInput.value = "";
                window.location.reload();
            }).fail(error => {
                alert("文件上传失败: " + error.toString());
            }).always(() => {
                // 恢复按钮状态
                $uploadBtn.prop("disabled", false).text("开始导入");
            });
        }

        // 动态加载题型统计信息并生成卡片
        function loadQuestionTypeStats() {
            $.ajax({
                url: "${pageContext.request.contextPath}/examquestionmanage/getQuestionTypeStats",
                type: "GET",
                dataType: "json",
                success: function(result) {
                    if (result && result.code === 1) {
                        generateStatsCards(result.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.log("加载题型统计信息失败:", error);
                }
            });
        }

        // 生成统计卡片
        function generateStatsCards(statsData) {
            const container = $("#statsCardsContainer");
            container.empty(); // 清空现有内容

            // 计算总题目数
            let totalCount = 0;
            if (statsData && Array.isArray(statsData)) {
                statsData.forEach(function(stat) {
                    if (stat && typeof stat.count === 'number') {
                        totalCount += stat.count;
                    }
                });
            }

            // 添加总题目数卡片
            const totalCard = '<div class="col-md-3">' +
                '<div class="card stats-card border-0 shadow-sm">' +
                '<div class="card-body">' +
                '<div class="d-flex justify-content-between">' +
                '<div>' +
                '<h6 class="text-muted">总题目数</h6>' +
                '<h3 class="text-primary">' + totalCount + '</h3>' +
                '</div>' +
                '<div class="text-primary">' +
                '<i class="bi bi-journal-text fs-1"></i>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';
            container.append(totalCard);

            // 为每种题型生成卡片
            if (statsData && Array.isArray(statsData)) {
                statsData.forEach(function(stat, index) {
                    const card = createStatCard(stat, index);
                    container.append(card);
                });
            }

            // 为每个卡片添加点击事件
            bindCardClickEvents();
        }

        // 创建单个统计卡片
        function createStatCard(stat, index) {
            // 定义不同题型的颜色和图标
            const colors = ['success', 'warning', 'info', 'primary', 'secondary'];
            const icons = ['bi-check-circle', 'bi-check-square', 'bi-pencil-square', 'bi-question-circle', 'bi-list'];

            const color = colors[index % colors.length];
            const icon = icons[index % icons.length];

            return'        <div class="col-md-3">' +
                '            <div class="card stats-card border-0 shadow-sm question-type-card" data-type-id="' + stat.typeId + '">' +
                '                <div class="card-body">' +
                '                    <div class="d-flex justify-content-between">' +
                '                        <div>' +
                '                            <h6 class="text-muted">' + stat.typeName + '</h6>' +
                '                            <h3 class="text-' + color + '">' + stat.count.toLocaleString() + '</h3>' +
                '                        </div>' +
                '                        <div class="text-' + color + '">' +
                '                            <i class="bi ' + icon + ' fs-1"></i>' +
                '                        </div>' +
                '                    </div>' +
                '                </div>' +
                '            </div>' +
                '        </div>' +
                '    ';
        }

        // 绑定卡片点击事件
        function bindCardClickEvents() {
            $(".question-type-card").off('click').on('click', function() {
                const typeId = $(this).data('type-id');

                // 只更新题型筛选下拉框的选中项，不触发题目列表更新
                $("#questionTypeFilter").val(typeId);

                // 添加选中样式
                $(".question-type-card").removeClass('active-card');
                $(this).addClass('active-card');
            });
        }

        // 动态加载课程列表
        $.ajax({
            url: "${pageContext.request.contextPath}/examquestionmanage/findAllCourse",
            type: "GET",
            dataType: "json",
            success: function(result) {
                if (result && result.code === 1) {
                    if (result.data && Array.isArray(result.data) && result.data.length > 0) {
                        var courseSelect = $("#courseFilter");
                        courseSelect.empty();
                        courseSelect.append('<option value="">所有课程</option>');

                        result.data.forEach(function(course) {
                            // 确保访问正确的属性
                            if (course && course.hasOwnProperty('id') && course.hasOwnProperty('name')) {
                                courseSelect.append('<option value="' + course.id + '">' + course.name + '</option>');
                            } else {
                                console.warn("课程对象缺少必要属性:", course);
                            }
                        });
                    } else {
                        console.log("返回的课程数据为空或不是有效数组:", result.data);
                    }
                } else {
                    console.log("接口返回错误码或数据格式不正确:", result);
                }
            },
            error: function(xhr, status, error) {
                console.log("加载课程列表失败:", error);
                console.log("HTTP状态:", status);
                console.log("响应内容:", xhr.responseText);
            }
        });

        // 动态加载课程列表
        $.ajax({
            url: "${pageContext.request.contextPath}/examquestionmanage/findAllQuestionType",
            type: "GET",
            dataType: "json",
            success: function(result) {
                if (result && result.code === 1) {
                    if (result.data && Array.isArray(result.data) && result.data.length > 0) {
                        var courseSelect = $("#questionTypeFilter");
                        courseSelect.empty();
                        courseSelect.append('<option value="">所有题型</option>');

                        result.data.forEach(function(questionType) {
                            // 确保访问正确的属性
                            if (questionType && questionType.hasOwnProperty('id') && questionType.hasOwnProperty('name')) {
                                courseSelect.append('<option value="' + questionType.id + '">' + questionType.name + '</option>');
                            } else {
                                console.warn("类型对象缺少必要属性:", questionType);
                            }
                        });
                    } else {
                        console.log("返回的类型数据为空或不是有效数组:", result.data);
                    }
                } else {
                    console.log("接口返回错误码或数据格式不正确:", result);
                }
            },
            error: function(xhr, status, error) {
                console.log("加载类型列表失败:", error);
                console.log("HTTP状态:", status);
                console.log("响应内容:", xhr.responseText);
            }
        });

        // 页面加载完成后，根据请求参数设置下拉框的选中状态
        $(document).ready(function() {
            // 设置课程下拉框选中项
            <c:if test="${not empty searchCourseId}">
            $("#courseFilter").val("${searchCourseId}");
            </c:if>

            // 设置题型下拉框选中项
            <c:if test="${not empty searchQuestionTypeId}">
            $("#questionTypeFilter").val("${searchQuestionTypeId}");
            </c:if>
        });

        // 添加查询按钮点击事件
        $("#searchBtn").on('click', function(e) {
            e.preventDefault();
            $("#searchForm").submit();
        });
        // 添加重置按钮点击事件
        $("#resetBtn").on('click', function() {
            $("#courseFilter").val("");
            $("#questionTypeFilter").val("");
            $("input[name='searchText']").val("");
        });
        // 定义删除按钮的功能
        const deleteBtnHandler = function () {
            const id = $(this).closest('div').data('id');
            if (id) {
                $.ajax({
                    url: "${pageContext.request.contextPath}/examquestionmanage/delete",
                    type: "POST",
                    data: {
                        questionId: id,
                    },
                    dataType: "json",
                }).done(result => {
                    if (!result) {
                        alert(result.message);
                        return;
                    }
                    alert(result.message);
                    window.location.reload();
                }).fail(() => {
                    alert(result.message);
                })
            }
        }

        // 定义编辑按钮的功能
        const editBtnHandler = function () {
            const id = $(this).closest('div').data('id');

            $.ajax({
                type: "GET",
                url: "${pageContext.request.contextPath}/examquestionmanage/findById",
                data: {
                    questionId: id,
                },
                dataType: "json",
            }).done(result => {
                if (result.code) {
                    $editModalBody.html("");
                    for (let item in result.data) {
                        const oDiv = document.createElement("div");
                        oDiv.className = "mb-3 w-100";
                        // 当item为typeId时，使用select标签
                        if (item === "typeId") {
                            // 先创建select元素
                            oDiv.innerHTML = `<label for="` + item + `" class="form-label">` + item + `</label>
                                <select class="form-select" id="typeId" name="typeId">
                                    <option value="0">请选择试题类型</option>
                                </select>
                            `;
                            // 通过AJAX获取题型数据
                            $.ajax({
                                type: "GET",
                                url: "${pageContext.request.contextPath}/questionType/findAll",
                                dataType: "json",
                                success: function (typeResult) {
                                    if (typeResult.code) {
                                        const selectElement = oDiv.querySelector("select");
                                        typeResult.data.forEach(function (questionType) {
                                            const option = document.createElement("option");
                                            option.value = questionType.id;
                                            option.textContent = questionType.name;
                                            if (questionType.id === result.data["typeId"]) {
                                                option.selected = true;
                                            }
                                            selectElement.appendChild(option);
                                        });
                                    }
                                }
                            });

                            $editModalBody.append(oDiv);
                            continue;
                        }
                        // 当item为courseId时，使用select标签
                        if (item === "courseId") {
                            oDiv.innerHTML = `<label for="` + item + `" class="form-label">` + item + `</label>
                                <select class="form-select" id="courseId" name="courseId">
                                    <option value="0">请选择题型所属课程</option>
                                </select>
                            `;

                            // 通过AJAX获取课程数据
                            $.ajax({
                                type: "GET",
                                url: "${pageContext.request.contextPath}/coursemanage/findAll",
                                dataType: "json",
                                success: function (courseResult) {
                                    if (courseResult.code) {
                                        const selectElement = oDiv.querySelector("select");
                                        courseResult.data.forEach(function (course) {
                                            const option = document.createElement("option");
                                            option.value = course.id;
                                            option.textContent = course.name;
                                            if (course.id == result.data["courseId"]) {
                                                option.selected = true;
                                            }
                                            selectElement.appendChild(option);
                                        });
                                    }
                                }
                            });

                            $editModalBody.append(oDiv);
                            continue;
                        }
                        oDiv.innerHTML = `
                            <label for="` + item + `" class="form-label">` + item + `</label>
                            <input type="text" class="form-control" id="` + item + `" placeholder="Example input placeholder" value="` + result.data[item] + `" />
                        `;
                        $editModalBody.append(oDiv);
                    }
                }
            }).fail(error => {
                console.log(error)
            });
        }

        // 模态框编辑按钮事件
        const editModalBtnHandler = function () {
            // 找到模态框里的所有input输入框
            const $inputs = $editModalBody.find('input');
            const $selects = $editModalBody.find('select');
            const data = {};

            $inputs.each((index, item) => {
                const key = $(item).attr('id');
                data[key] = $(item).val();
            });

            $selects.each((index, item) => {
                const key = $(item).attr('id');
                data[key] = $(item).val();
            });

            $.post("${pageContext.request.contextPath}/examquestionmanage/update", {
                    ...data,
                }, null, "json"
            ).done(result => {
                if (!result.code) {
                    alert(result.message);
                    return;
                }
                alert(result.message);
                $editModal.modal('hide');
                // 刷新页面内容
                window.location.reload();
            }).fail(error => {
                alert(result.message);
                console.log(error);
            });
        }

        // 添加
        const addBtnHandler = function () {
            // 找到模态框里的所有input输入框
            const $inputs = $addModalBody.find('input');
            const $selects = $addModalBody.find('select');
            const $switcher = $addModalBody.find('#state');
            const data = {};

            $inputs.each((index, item) => {
                const key = $(item).attr('id');
                data[key] = $(item).val();
            });

            $selects.each((index, item) => {
                const key = $(item).attr('id');
                data[key] = $(item).val();
            });
            data["state"] = $switcher.prop('checked');

            $.post("${pageContext.request.contextPath}/examquestionmanage/add", {
                    ...data,
                }, null, "json"
            ).done(result => {
                if (!result.code) {
                    alert("添加失败，请重新提交");
                    return;
                }
                alert("添加成功");
                $editModal.modal('hide');
                // 刷新页面内容
                window.location.reload();
            }).fail(error => {
                alert("添加失败，请重新提交");
                console.log(error);
            });
        }

        // 绑定事件 箭头函数不会创建自己的 this 上下文
        $uploadBtn.click(uploadBtnHandler);
        $deleteBtns.on('click', deleteBtnHandler);
        $editBtns.on('click', editBtnHandler);
        $editModalBtn.on('click', editModalBtnHandler);
        $addModalBtn.on('click', addBtnHandler);

        // 模态框隐藏时重置表单
        $uploadModal.on('hidden.bs.modal', function () {
            fileInput.value = "";
            $uploadBtn.prop("disabled", false).text("开始导入");
        });

        loadQuestionTypeStats();
    });
</script>
<jsp:include page="footer.jsp"/>
